package com.fingard.dsp.bank.directbank.spdb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.Date;


public class SPDB01Statement extends SPDB01Base implements IStatement {
    @Override
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();

        String[] tmpPayRecRespHeader = getPayRecStatement(p_reqQrySttm, retAts);
        String tmpPayRecTotalNum = getTotalNum(retAts.totalNum);


        if ("-1".equals(tmpPayRecRespHeader[0])) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("对账单获取失败,原因:" + tmpPayRecRespHeader[1]);
        } else {
            if (retAts.getWrittenRdCount() == 0) {
                retAts.writeRespCode("0");
                String respInfo = tmpPayRecRespHeader[1];
                if (StringHelper.isNullOrEmpty(respInfo)) {
                    respInfo = "交易为空";
                }
                retAts.writeRespInfo(respInfo);
            } else {
                retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(tmpPayRecTotalNum)));
            }
        }

        retAts.writeEnd();
        return retAts;
    }


    private String[] getPayRecStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
        String[] respHeader = new String[]{"", ""};

        String tmpRespCode = "";
        String tmpRespInfo = "";

        retAts.totalNum = "0";
        int totalNum = 0;
        try {
            SPDB01Header bankHeader = new SPDB01Header();
            XmlTextWriter xmlWriterAT21 = new XmlTextWriter();
            bankHeader.transCode = "AT21";
            String ownAct = p_reqQrySttm.actNum;
            xmlWriterAT21.writeStartElement("body");
            xmlWriterAT21.writeElementString("transMasterID", getBankConfig().getMapValueByKey("transMasterIDMapping", ownAct));//交易客户号
            xmlWriterAT21.writeElementString("projectNumber", getBankConfig().getMapValueByKey("projectNumberMapping", ownAct));//项目编码
            xmlWriterAT21.writeElementString("costItemCode", getBankConfig().getMapValueByKey("costItemCodeMapping", ownAct));//费项编码
            xmlWriterAT21.writeElementString("transDate", Format.Date8Format.format(new Date()));
            xmlWriterAT21.writeElementString("reconMode", "0");
            xmlWriterAT21.writeElementString("reconDate", Format.Date8Format.format(p_reqQrySttm.getBusDate()));
            xmlWriterAT21.writeElementString("organReconTransBeginTime", "");
            xmlWriterAT21.writeElementString("organReconTransEndTime", "");
            String orderType = getBankConfig().getValueAsString("orderType");
            String transType = getBankConfig().getValueAsString("transType");
            if (StringHelper.isNullOrEmpty("orderType")) {
                orderType = "3";
            }
            if (StringHelper.isNullOrEmpty("transType")) {
                transType = "3";
            }
            xmlWriterAT21.writeElementString("orderType", orderType);// 订单类型 1:单笔，2:批量，3:全部
            xmlWriterAT21.writeElementString("transType", transType);// 交易类型 1:代收，2:代付，3:代收付
            xmlWriterAT21.writeEndDocument();

            String[] tmpStrRetAT21 = sendToBank(xmlWriterAT21.toXmlString(), bankHeader);

            XmlTextReader tmpBkReader;
            if (tmpStrRetAT21[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                tmpBkReader = loadBankRespXmlReader(tmpStrRetAT21[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpReturnCode = tmpBkReader.getFirstText("/packet/head/returnCode");
                    String tmpReturnMsg = tmpBkReader.getFirstText("/packet/head/returnMsg");
                    if ("AAAAAAA".equals(tmpReturnCode)) {
                        String reconRequestHandleStatus = tmpBkReader.getFirstText("/packet/body/reconRequestHandleStatus");// 0-受理成功，1-受理失败
                        String reconHandleSeqNo = tmpBkReader.getFirstText("/packet/body/reconHandleSeqNo");// 对账受理编号
                        if ("0".equals(reconRequestHandleStatus) && StringHelper.hasAnyChar(reconHandleSeqNo)) {
                            boolean tmpEndFlag = false;
                            int queryPage = 0;
                            String tmpFileName = "";
                            while (!tmpEndFlag) {
                                queryPage++;
                                XmlTextWriter xmlWriterAT22 = new XmlTextWriter();
                                bankHeader.transCode = "AT22";
                                xmlWriterAT22.writeStartElement("body");
                                xmlWriterAT22.writeElementString("transMasterID", getBankConfig().getMapValueByKey("transMasterIDMapping", ownAct));//交易客户号
                                xmlWriterAT22.writeElementString("projectNumber", getBankConfig().getMapValueByKey("projectNumberMapping", ownAct));//项目编码
                                xmlWriterAT22.writeElementString("costItemCode", getBankConfig().getMapValueByKey("costItemCodeMapping", ownAct));//费项编码
                                xmlWriterAT22.writeElementString("transDate", Format.Date8Format.format(new Date()));
                                xmlWriterAT22.writeElementString("reconHandleSeqNo", reconHandleSeqNo);
                                xmlWriterAT22.writeElementString("queryPage", String.valueOf(queryPage));
                                xmlWriterAT22.writeElementString("fileName", tmpFileName);
                                xmlWriterAT21.writeEndDocument();

                                String[] tmpStrRetAT22 = sendToBank(xmlWriterAT21.toXmlString(), bankHeader);
                                if (tmpStrRetAT22[0].length() == 0) {
                                    StringBuilder tmpSbMsgAT22 = new StringBuilder();
                                    tmpBkReader = loadBankRespXmlReader(tmpStrRetAT22[1], tmpSbMsg);
                                    if (tmpBkReader != null) {
                                        String returnCode = tmpBkReader.getFirstText("/packet/head/returnCode");
                                        String returnMsg = tmpBkReader.getFirstText("/packet/head/returnMsg");
                                        if ("AAAAAAA".equals(returnCode)) {
                                            String totalNumber = tmpBkReader.getFirstText("/packet/body/totalNumber");
                                            String reconHandleStatus = tmpBkReader.getFirstText("/packet/body/reconHandleStatus");
                                            String endFlag = tmpBkReader.getFirstText("/packet/body/endFlag");
                                            String fileName = tmpBkReader.getFirstText("/packet/body/fileName");
                                            if ("1".equals(endFlag)) {
                                                tmpEndFlag = true;
                                            }
                                            tmpFileName = fileName;
                                            if ("0".equals(reconHandleStatus)) {
                                                while (tmpBkReader.read("/packet/body/lists/list")) {
                                                    String detailedContent = tmpBkReader.readedXElement.getSingleText("detailedContent");
                                                    if (StringHelper.hasAnyChar(detailedContent)) {
                                                        StringReader strReader = new StringReader(detailedContent);
                                                        BufferedReader tmpReader = new BufferedReader(strReader);
                                                        while (true) {
                                                            String eachline = tmpReader.readLine();
                                                            if (eachline == null) {
                                                                break;
                                                            }
                                                            if (eachline.indexOf('|') > 0) {
                                                                totalNum++;
                                                                RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                                                                String[] detailNodes = eachline.split("\\|");
                                                                String cdFlag = detailNodes[1];
                                                                if ("1".equals(cdFlag)) {// 代收
                                                                    tmpRetDetail.cdFlag = "22";
                                                                } else if ("2".equals(cdFlag)) {// 代付
                                                                    tmpRetDetail.cdFlag = "27";
                                                                }
                                                                tmpRetDetail.askNumber = detailNodes[2];
                                                                tmpRetDetail.oppAct = detailNodes[8];
                                                                tmpRetDetail.oppActName = detailNodes[9];
                                                                tmpRetDetail.oppActName = detailNodes[9];
                                                                tmpRetDetail.oppActName = detailNodes[9];
                                                                tmpRetDetail.oppBank = detailNodes[11];
                                                                tmpRetDetail.cur = this.convertCurToATS(detailNodes[13]);
                                                                tmpRetDetail.amount = detailNodes[14];

                                                                tmpRetDetail.busTime = detailNodes[15].substring(0, 4) + "-" + detailNodes[15].substring(4, 6) + "-" + detailNodes[15].substring(6, 8) + " " + detailNodes[15].substring(8, 10) + ":" + detailNodes[15].substring(10, 12) + ":" + detailNodes[15].substring(12, 14);
                                                                tmpRetDetail.summary = detailNodes[17];
                                                                tmpRetDetail.memo = detailNodes[18];
                                                                String state = detailNodes[16];// 交易状态 0-成功；1-失败；2-处理中
                                                                if ("0".equals(state)) {
                                                                    tmpRetDetail.transState = TransState.Success;
                                                                } else if ("1".equals(state)) {
                                                                    tmpRetDetail.transState = TransState.Fail;
                                                                } else if ("2".equals(state)) {
                                                                    tmpRetDetail.transState = TransState.Paying;
                                                                }
                                                                retAts.writeRetDetail(tmpRetDetail);
                                                            } else {
                                                                tmpRespCode = "-1";
                                                                tmpRespInfo = "银行返回对账结果明细数据格式非法!";
                                                            }
                                                        }
                                                    } else {
                                                        tmpRespCode = "-1";
                                                        tmpRespInfo = "对账结果明细内容为空!";
                                                    }
                                                }
                                            }
                                        } else {
                                            tmpRespCode = "-1";
                                            tmpRespInfo = returnMsg;
                                        }
                                    } else {
                                        tmpRespCode = "-1";
                                        tmpRespInfo = tmpSbMsgAT22.toString();
                                    }
                                } else {
                                    tmpRespCode = "-1";
                                    tmpRespInfo = tmpStrRetAT22[1];
                                }
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpReturnMsg;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpReturnMsg;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = tmpStrRetAT21[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.totalNum = String.valueOf(totalNum);

        respHeader[0] = tmpRespCode;
        respHeader[1] = tmpRespInfo;

        return respHeader;
    }
}